// pages/groupPurchase/groupPurchase.js
const teamBuyService = require('../../../../api/teamBuyService.js')
const storeService = require('../../../../api/storeService.js')
const productService = require('../../../../api/productService.js')
const util = require('../../../../utils/utils.js')

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    description: '',
    teamLeaderPrice: '',
    teamMemberPrice: '',
    teamMemberCount: '',
    teamMemberJoinCount: '',
    joinMemberCount: '',
    productDetails: {},
    productName: '',
    simulateJoin: '',
    stores: [],
    storeId: [],
    storeName: '',
    teamBuyingStatus: '',
    teamBuyingType: '',
    countDownList: {},
    originalPrice: '',
    teamBuyTimeList: [],
    goodsList: [],
    tabSelected: '0',
    category: [],
    leaderImageUrl: '',
    memberImageUrl: '',
    teamBuying: [],
    sellPrice: '',
    teamBuyEnd: false,
    endTime: '',
    groupTimeId: 0,
    phone: false,
    orderSelfScope: ''
  },
  joinGroup: function () {
    var self = this
    const loginStatus = this.checkAuth()
    if (loginStatus) {
      let goodsList = []
      goodsList.push(self.data.productDetails)
      let teamBuy = {
        goodsPrice: this.data.teamBuying.teamMemberPrice,
        storeId: this.data.storeId,
        storeName: this.data.storeName,
        goodsList: [],
        teamBuyId: this.data.teamBuying.id,
        teamLeaderRecordId: this.data.teamBuying.teamLeaderRecordId,
        orderType: 'group',
        teamBuyInfo: {
          endTime: self.data.endTime,
          orderSelfScope: self.data.orderSelfScope
        },
        scource: 'BUYNOW'
      }
      goodsList.forEach(item => {
        item = {
          ...item,
          productId: item.id,
          productNum: 1,
          sellPrice: self.data.sellPrice
        }
        console.log(item)
        teamBuy.goodsList.push(item)
      })
      console.log(teamBuy)
      wx.setStorageSync('wj_shopcart', teamBuy)
      if (self.data.teamMemberCount - self.data.joinMemberCount == 0) {

      } else {
        if (app.globalData.userInfo.member) {
          wx.navigateTo({
            url: '../../order/perfectOrder/perfectOrder'
          })
        } else {
          self.handlePopupPhone()
        }
      }
    } else {

    }
  },
  // 获取当前门店的所有分类和商品
  getMenuProduct: function (storeId) {
    const that = this
    productService.getMenuProduct(storeId, "RETAIL").then(res => {
      console.log(res)
      if (res != '') {
        let selected = this.data.tabSelected
        let tempGoodsList = []
        res.forEach(item => {
          var tempData = that.productsSort(item.products)
          let tempList = []
          console.log(tempData)
          tempData.forEach(data => {
            let produtlabel = []
            let promotions = []
            let specifications = null
            if (data.labels && data.labels.length > 0) {
              data.labels.forEach(ele => {
                if (ele.type === 'GOODSLABEL') {
                  produtlabel.push(ele)
                } else if (ele.type === 'PROMOTIONLABEL') {
                  promotions.push(ele)
                }
              })
            }
            if (data.productProperties && data.productProperties.length > 0) {
              for (let i = 0; i < data.productProperties.length; i++) {
                const ele = data.productProperties[i];
                if (ele.propertyName === '规格') {
                  specifications = ele.propertyValue
                  break
                } else {}

              }
            }
            let tempItem = {
              ...data,
              produtlabel: produtlabel,
              promotions: promotions,
              specifications: specifications ? specifications : ''
            }
            tempList.push(tempItem)
          })
          tempGoodsList.push(tempList)
        })
        this.setData({
          category: res,
          goodsList: tempGoodsList
        })
        console.log(this.data.goodsList)
      }

    })
  },
  productsSort: function (array) {
    let balanceArray = []
    let allArray = []
    array.forEach(ele => {
      if (ele.balance === 0) {
        balanceArray.push(ele)
      } else {
        allArray.push(ele)
      }
    });
    const tempArray = allArray.concat(balanceArray)
    return tempArray
  },
  // 查询团购商品数据
  queryGoods: function (storeId) {
    const self = this
    if (this.options.teamBuyId) {
      var teamBuyId = self.options.teamBuyId
      var teamLeaderRecordId = self.options.teamLeaderRecordId
      teamBuyService.getDetailsByStoreId(teamBuyId, storeId, teamLeaderRecordId).then(res => {
        console.log(res)
        if (res) {
          this.setData({
            id: res.id,
            name: res.name ? res.name : '',
            description: res.description ? res.description : '',
            leaderImageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/userImg1.png',
            teamMemberImageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/userImg1.png',
            teamLeaderPrice: res.teamLeaderPrice ? res.teamLeaderPrice : res.teamMemberPrice,
            teamMemberPrice: res.teamMemberPrice ? res.teamMemberPrice : '',
            teamMemberCount: res.teamMemberCount ? res.teamMemberCount : '',
            teamMemberJoinCount: res.teamMemberJoinCount,
            joinMemberCount: res.joinMemberCount ? res.joinMemberCount : 0,
            joinMbrs: res.joinMbrs,
            openTeamTime: res.openTeamTime, //开团时间
            duration: res.duration, //持续时间
            productDetails: res.productDetails,
            productName: res.productName,
            simulateJoin: res.simulateJoin,
            stores: res.stores,
            originalPrice: res.productDetails.originalPrice ? res.productDetails.originalPrice : '',
            teamBuyingStatus: res.teamBuyingStatus,
            teamBuyingType: res.teamBuyingType,
            teamBuying: res,
            endTime: res.endTime,
            orderSelfScope: res.orderSelfScope
          })
          console.log(self.data.joinMbrs)
          let storeId = self.data.storeId
          let goodsId = self.data.productDetails.id
          productService.getDetails(storeId, goodsId).then(res => {
            self.setData({
              sellPrice: res.sellPrice
            })
          })
          var data = new Date()
          var nowDate = new Date().getTime();
          let openTiem = 0
          if (self.data.openTeamTime) {
            openTiem = new Date(self.data.openTeamTime.replace(/-/g, '/')).getTime()
          } else {
            openTiem = nowDate
            self.setData({
              openTeamTime: (util.formatTime(data)).replace(/\//g, '-')
            })
            console.log(self.data.openTeamTime)
          }
          let duration = (nowDate - openTiem) / 1000
          if (duration >= self.data.duration) {
            self.setData({
              teamBuyEnd: true
            });
          }
          if (self.data.teamBuyEnd === false) {
            // 获取倒计时
            let teamBuyTimeInfo = [];
            // 将活动的结束时间参数提成一个单独的数组，方便操作
            let tempTime = {
              openTeamTime: this.data.openTeamTime,
              duration: this.data.duration
            }
            teamBuyTimeInfo.push(tempTime)

            this.setData({
              teamBuyTimeList: teamBuyTimeInfo
            });
            countDown()
            // 执行倒计时函数
            function countDown() {
              clearTimeout(self.data.groupTimeId)
              self.setData({
                countDownList: util.countDown(teamBuyTimeInfo)[0]
              })
              if (self.data.countDownList.hou == '00' && self.data.countDownList.min == '00' && self.data.countDownList.sec == '00') {
                self.setData({
                  teamBuyEnd: true
                })
              }
              let time = setTimeout(
                function () {
                  countDown(teamBuyTimeInfo);
                }, 1000)
              self.setData({
                groupTimeId: time
              })
            }
          } else {

          }
        } else {
          wx.showModal({
            title: '提示',
            content: '当前门店没有该商品的团购活动，可以看看别的拼团活动哦~',
            cancelText: '随便逛逛',
            success: function (res) {
              if (res.confirm) {
                wx.switchTab({
                  url: '../fightGroup/fightGroup'
                })
              } else if (res.cancel) {
                wx.switchTab({
                  url: '../../index/index/index'
                })
              }
            }
          })
        }
      }).catch(err => {
        console.log(err.message)
        wx.showModal({
          title: '提示',
          content: '当前门店没有该商品的团购活动，可以看看别的拼团活动哦~',
          cancelText: '随便逛逛',
          success: function (res) {
            if (res.confirm) {
              wx.switchTab({
                url: '../fightGroup/fightGroup'
              })
            } else if (res.cancel) {
              wx.switchTab({
                url: '../../index/index/index'
              })
            }
          }
        })
      })
    }
    this.getMenuProduct(this.data.storeId)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var self = this
    // 判断globalData.storeInfo有没有数据，有数据，则使用选择的门店数据，没有，则根据当前地理位置获取最近门店
    console.log(app.globalData.storeInfo)
    if (app.globalData.storeInfo) {
      self.setData({
        storeId: app.globalData.storeInfo.id,
        storeName: app.globalData.storeInfo.name,
      })
      self.queryGoods(app.globalData.storeInfo.id)
      console.log("1")
    } else {
      console.log("13")
      // 获取当前地理位置，然后筛选出最近的门店，根据当前门店获取门店的商品
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          var latitude = res.latitude
          var longitude = res.longitude
          try {
            var tempAllStores = wx.getStorageSync('wj_allStores'); // 获取缓存的所有门店
            if (tempAllStores) {
              // Do something with return value
              let tempIndex = self.getNearestStore(tempAllStores, latitude, longitude);
              app.globalData.storeInfo = tempAllStores[tempIndex];
              // 获取商品详情
              console.log("2")
              self.queryGoods(tempAllStores[tempIndex].id)
            } else {
              // 查询所有门店
              console.log("3")
              storeService.queryList().then(res => {
                var allStores = [];
                res.forEach(item => {
                  if (item.status === 'OPEN') {
                    allStores.push(item)
                  }
                });
                try {
                  wx.setStorageSync('wj_allStores', allStores)
                } catch (e) {
                  console.log(e)
                }
                let tempIndex = self.getNearestStore(allStores, latitude, longitude);
                return allStores[tempIndex]
              }).then(res => {
                app.globalData.storeInfo = res;
                self.queryGoods(res.id)
              })
            }
          } catch (e) {
            console.log(e)
            // Do something when catch error
          }
        }
      })
    }
    if (self.options.mobile && self.options.mobile != '' && self.options.mobile != undefined) {
      const mobile = self.options.mobile
      try {
        wx.setStorageSync('wj_sharingId', mobile)
      } catch (e) {}
    }
  },
  // 获取最近的一家门店
  getNearestStore: function (allStores, latitude, longitude) {
    var distanceArr = [];
    allStores.forEach(item => {
      let dis = util.distance(latitude, longitude, item.latitude, item.longitude);
      distanceArr.push(dis);
    })
    // 计算最小值
    const minN = Math.min.apply(Math, distanceArr);
    let tempIndex = 0;
    for (var i = 0; i < distanceArr.length; i++) {
      if (minN === distanceArr[i]) {
        tempIndex = i;
        break;
      }
    }
    this.setData({
      stores: allStores[tempIndex],
      storeName: allStores[tempIndex].name,
      storeId: allStores[tempIndex].id
    })
    return tempIndex;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.phone === true) {
      this.handlePopupPhone()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimeout(this.data.groupTimeId)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const that = this
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      let memberId = app.globalData.userInfo.member.id
      var pages = getCurrentPages() //获取加载的页面
      var currentPage = pages[pages.length - 1] //获取当前页面的对象
      var url = currentPage.route //当前页面url
      var options = currentPage.options //如果要获取url中所带的参数可以查看options
      console.log(url, options)
      let path = url + '?mobile=' + memberId
      for (const key in options) {
        if (options.hasOwnProperty(key)) {
          const ele = options[key];
          path = path + '&' + key + '=' + ele
        }
      }
      console.log(path)
      return {
        path: path,
        imageUrl: that.data.productDetails.imageUrl,
        success(e) {
          wx.showShareMenu({
            withShareTicket: true
          })
        }
      }
    } else {
      return {
        imageUrl: that.data.productDetails.imageUrl,
        success(e) {
          wx.showShareMenu({
            withShareTicket: true
          })
        }
      }
    }
  },
  toHome: function () {
    wx.switchTab({
      url: '../../index/index/index'
    })
  },
  // 类目点击事件
  clickCategory: function (e) {
    this.setData({
      tabSelected: e.currentTarget.dataset.idx
    })
  },
  toGoodsDetail: function (val) {
    wx.navigateTo({
      url: '../../goods/goodsDetail/goodsDetail?productId=' + val.currentTarget.id + '&storeId=' + this.data.storeId + '&type=normal'
    })
  },
  // 检查当前用户是否登录授权
  checkAuth: function () {
    var self = this;
    if (!app.globalData.userInfo) {
      wx.showModal({
        title: '提示',
        content: '请同意授权获取用户信息',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            try {
              // 缓存页面参数信息，跳转授权页面
              let pageUrl = '../groupPurchase/groupPurchase?teamBuyId=' + self.options.teamBuyId + '&teamLeaderRecordId=' + self.options.teamLeaderRecordId
              if (self.options.storeData) {
                pageUrl = pageUrl + '&storeData=' + self.options.storeData
              }
              wx.setStorageSync('wj_pageUrl', pageUrl)
            } catch (e) {
              console.log(e.message)
            }
            wx.switchTab({
              url: '../../member/my/my'
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return false;
    } else {
      return true;
    }
  },
  // 用户登录组件事件处理
  handleUserLogin: function () {
    console.log(app.globalData.userInfo)
    const self = this
    if (app.globalData.userInfo) {
      const user = app.globalData.userInfo
      this.setData({
        userInfo: {
          ...user.wxaUser
        }
      })
      if (app.globalData.userInfo.member) {
        self.setData({
          hasUserInfo: true,
        })
      } else {
        self.setData({
          userInfo: user.wxaUser,
          hasUserInfo: true,
        })
      }
    }
  },
  handlePopupPhone: function () {
    if (!app.globalData.userInfo.member) {
      this.setData({
        phone: true
      });
    } else {
      this.setData({
        phone: false
      })
    }
  },
  handleBindPhone: function (e) {
    console.log(e.detail)
    if (e.detail.bindMobile === true) {
      this.handlePopupPhone()
    }
  }
})